import { User } from '@libs/db/models/user.model'
import { Body, Controller, Get, HttpCode, Post, Req, UseGuards } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { ApiBearerAuth, ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger'
import { ReturnModelType } from '@typegoose/typegoose'
import { InjectModel } from 'nestjs-typegoose'
import { JwtService } from '@nestjs/jwt'
import { Role } from '@libs/db/models/role.model'
import { AuthService } from './auth.service'
import { MenusService } from 'src/menus/menus.service'
import { Menu } from '@libs/db/models/menu.model'

export class LoginDto {
  @ApiProperty({ description: '用户名' })
  username: string
  @ApiProperty({ description: '密码' })
  password: string
}

@Controller('auth')
@ApiTags('授权')
export class AuthController {
  constructor(
    private jwtService: JwtService,
    private authService: AuthService,
    private menuServie: MenusService,
    @InjectModel(User) private readonly userModel: ReturnModelType<typeof User>,
    @InjectModel(Role) private readonly roleModel: ReturnModelType<typeof Role>,
  ) {}

  @Post('register')
  @ApiOperation({ summary: '注册' })
  async register(@Body() dto: User): Promise<MyResponseType<null>> {
    const res = await this.userModel.findOne({ username: dto.username })
    if (res) {
      return { code: 501, message: '用户名已存在!', data: null }
    } else {
      await this.userModel.create(dto)
      return { code: 200, message: '注册成功!', data: null }
    }
  }

  @Post('login')
  @ApiOperation({ summary: '登录' })
  @HttpCode(200)
  @UseGuards(AuthGuard('local'))
  async login(@Req() req): Promise<MyResponseType<string>> {
    return {
      code: 200,
      data: this.jwtService.sign(String(req.user._id)),
      message: '登录成功',
    }
  }

  @Get('user')
  @ApiOperation({ summary: '获取用户信息' })
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  async getUser(@Req() req): Promise<User> {
    return req.user
  }

  @Get('menu')
  @ApiOperation({ summary: '获取权限菜单' })
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  async getMenu(@Req() { user }): Promise<MyResponseType<Menu[]>> {
    let menuIds: string[] = []
    if (user.roleId) {
      const { menuId } = await this.roleModel.findOne({
        _id: String(user.roleId),
      })
      menuIds = menuId || []
    }

    const menuList = await this.menuServie.getMenu('0')
    const data = this.authService.createPremissonMenu(menuList, menuIds)
    return {
      code: 200,
      message: '成功',
      data,
    }
  }
}
